package io.lvdaxian.mybatis15.session.defaults;


import io.lvdaxian.mybatis15.executor.Executor;
import io.lvdaxian.mybatis15.mapping.Environment;
import io.lvdaxian.mybatis15.session.Configuration;
import io.lvdaxian.mybatis15.session.SqlSession;
import io.lvdaxian.mybatis15.session.SqlSessionFactory;
import io.lvdaxian.mybatis15.session.TransactionIsolationLevel;
import io.lvdaxian.mybatis15.transaction.Transaction;
import io.lvdaxian.mybatis15.transaction.TransactionFactory;

import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {
  
  private final Configuration configuration;
  
  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }
  
  @Override
  public SqlSession openSession() {
    Transaction tx = null;
    
    try {
      // 从这里拿到上下文环境信息
      Environment environment = configuration.getEnvironment();
      TransactionFactory transactionFactory = environment.getTransactionFactory();
      // 构建事务
      tx = transactionFactory.newTransaction(environment.getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);
      
      // 拿到执行器
      Executor executor = configuration.newExecutor(tx);
      
      return new DefaultSqlSession(configuration, executor);
    } catch (Exception e) {
      try {
        assert tx != null;
        tx.close();
      } catch (SQLException ignore) {
      }
      throw new RuntimeException("Error opening session.  Cause: " + e);
    }
  }
}
